/**
 * Created by sunzhijun on 2019/01/01.
 */
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import ReferSearch from '../../../../hrpub/common/components/referSearch/org';
import {high, createPage, base, getUrlParam, toast, promptBox} from 'nc-lightapp-front';
import {hrAjax as ajax} from 'src/hrpub/common/utils/utils';
import printPage from '../../control_glb/main/functions/print';
import {handleHash} from 'src/hrpub/common/utils/utils';
import './index.less';

let tableid = 'seqcontrollist';
let modifyDataArr = [];
const appcode = "60070530", pagecode = "60070530p", format = "YYYY-MM-DD";
const {NCTable, NCDatePicker, NCModal, NCButton} = base;

const moduleId = "hihr6007"
const domainName = "hrhi"

class MainPage extends Component {
    constructor(props) {
        super(props);
        if (props.use) {
            props.use.editTable(tableid);
        }
        this.config = {
            pagecode: pagecode,
            appcode: appcode
        };
        this.state = {
            showMode: 'browse',
            hrDeptTreeRef: '',                      // 人力资源部门参照
            queryActionPkorg: '',       //refpk
            checkedRowData: '',         //每一行的数据
            defaultCheckedRowData: ''   //默认选择行数据
        }
        props.createUIDom(this.config, (data) => {
            this.setState({
                buttons: data.button || [],
                context: data.context || {},
                pk_org: data.context.pk_org,
                telName: data.template.name || ''
            });
            props.meta.setMeta(data && data.template ? data.template : {});
            props.button.setButtons(data && data.button ? data.button : {});
        });
        this.getRowData = this.getRowData.bind(this);
        this.onBeforeEvent = this.onBeforeEvent.bind(this);
        this.checkedOrNot = this.checkedOrNot.bind(this);
    }

    componentWillMount() {
        window.location.hash = '?page=201908241349';
        let callback = (json, status, inlt) => {
            if (status) {
                this.lang = json
                this.setState({json, inlt})//存json和inlt到页面state中并刷新页面
            }
        }
        this.props.MultiInit.getMultiLang({moduleId: moduleId, domainName: domainName, callback})
    }

    componentDidMount() {
        this.props.button.setButtonDisabled('edit', true);
        this.updateButtonStatus();
        // 计算列表的高度
        // let bodyH = this.refs.getContainerDom.offsetHeight;
        // let headerH = this.refs.getHeaderDom.offsetHeight;
        // this.setState({
        //     tableHeight: bodyH - headerH - 44
        // })
    }

    //数据初始化
    fetchTableData(args) {
        ajax({
            url: '/nccloud/hrhi/seqcontrol/InitSeqcontrolAction.do',
            data: {
                'pk_org': args || this.state.queryActionPkorg,
            },
            success: res => {
                if (res.success) {
                    this.props.editTable.setTableData(tableid, {rows: res.data && res.data.grid.seqcontrollist.rows || []});
                    if (!res.data) {
                        this.props.button.setButtonDisabled('edit', true);
                    } else {
                        if (!!res.data.isenable) {
                            this.props.button.setButtonDisabled('edit', false);
                            this.props.editTable.focusRowByIndex(tableid, 0);
                            let defaultData = [];
                            defaultData.push(res.data.grid.seqcontrollist.rows[0]);
                            this.setState({
                                checkedRowData: defaultData  //默认选择第一行数据
                            });
                        } else {
                            this.props.button.setButtonDisabled('edit', true);
                        }
                    }
                    this.updateShowMode('browse');
                }
            }
        })
    }

    //保存
    saveTableData() {

        let modelInfo = {
            model: ({
                rows: modifyDataArr
            }),
            pk_org: this.state.queryActionPkorg
        }
        ajax({
            url: '/nccloud/hrhi/seqcontrol/SaveSeqcontrol1Action.do',
            type: 'post',
            data: modelInfo,
            success: res => {
                if (res.success) {
                    this.saveTableData2(modelInfo)
                } else {
                    promptBox({
                        color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
                        title: this.state.json['hihr-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
                        content: res.data.confirmMsg,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
                        noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
                        noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
                        beSureBtnName: this.state.json['hihr-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
                        cancelBtnName: this.state.json['hihr-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
                        hasCloseBtn: true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
                        beSureBtnClick: () => {
                            this.saveTableData2(modelInfo)
                        },   // 确定按钮点击调用函数,非必输
                        // cancelBtnClick: functionCancel,  // 取消按钮点击调用函数,非必输
                        // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
                        closeByClickBackDrop: false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
                    })
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
                if (this.state.showMode === 'browse') {
                    this.fetchTableData()
                }
                // this.props.editTable.cancelEdit(tableid);
            }
        })
    }

    //保存2
    saveTableData2(data) {
        ajax({
            url: '/nccloud/hrhi/seqcontrol/SaveSeqcontrol2Action.do',
            type: 'post',
            data: data,
            success: res => {
                this.fetchTableData();
                modifyDataArr = [];
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
                if (this.state.showMode === 'browse') {
                    this.fetchTableData()
                }
                // this.props.editTable.cancelEdit(tableid);
            }
        })
    }

    //确认弹窗
    promptBoxModal(context, func, args) {
        promptBox({
            color: 'warning',               // 提示类别默认"success"， "success"/"info"/"warning"/"danger",非必输
            title: this.state.json['hihr-000003'],                // 提示标题, 默认不同类别下分别为："已成功"/"帮助信息"/"请注意"/"出错啦",非必输/* 国际化处理： 确认删除*/
            content: context,             // 提示内容,非必输/* 国际化处理： 您确定要删除所选数据么?*/
            noFooter: false,                // 是否显示底部按钮(确定、取消),默认显示(false),非必输
            noCancelBtn: false,             // 是否显示取消按钮,，默认显示(false),非必输
            beSureBtnName: this.state.json['hihr-000006'],          // 确定按钮名称, 默认为"确定",非必输/* 国际化处理： 确定*/
            cancelBtnName: this.state.json['hihr-000007'],         // 取消按钮名称, 默认为"取消",非必输/* 国际化处理： 取消*/
            hasCloseBtn: true,             //显示“X”按钮，默认不显示，不显示是false，显示是true
            // beSureBtnClick: ()=>{ this.resetTableData() },   // 确定按钮点击调用函数,非必输
            beSureBtnClick: () => {
                func(args)
            },   // 确定按钮点击调用函数,非必输
            // cancelBtnClick: functionCancel,  // 取消按钮点击调用函数,非必输
            // closeBtnClick:functionClose, //关闭按钮点击调用函数，非必输
            closeByClickBackDrop: false,//点击遮罩关闭提示框，默认是true点击关闭，阻止关闭是false
        })
    }

    // //重置数据
    // resetTableData(){
    //     ajax({
    //         url: '/nccloud/hrhi/seqcontrol/ResetSeqcontrolAction.do',
    //         type: 'post',
    //         data: {
    //             'pk_org': this.state.context.pk_org,
    //         },
    //         success: res => {
    //             if (res.success) {
    //                 this.updateShowMode('browse');
    //                 this.fetchTableData()
    //                 toast({color:"success"})
    //             } 
    //         },
    //         error: rej => {
    //             toast({color:"warning",content: rej.message})
    //         }
    //     })
    // }
    //刷新
    refreshTableData() {
        ajax({
            url: '/nccloud/hrhi/seqcontrol/RefreshSeqcontrolAction.do',
            type: 'post',
            data: {
                'pk_org': this.state.context.pk_org,
            },
            success: res => {
                if (res.success) {
                    this.updateShowMode('browse');
                    this.fetchTableData()
                    toast({color: "success"})
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
    }

    // 按钮是否显示，按钮是否可用
    updateButtonStatus() {
        var showMode = this.state.showMode
        this.props.button.setButtonsVisible({
            set: showMode === 'browse',
            edit: showMode === 'browse',
            refresh: showMode === 'browse',
            reset: showMode === 'browse',
            save: showMode === 'edit',
            cancel: showMode === 'edit',
            print: showMode === 'browse'
        })
    }

    // 更新界面状态
    updateShowMode(showMode) {
        var oldMode = this.state.showMode;
        this.setState({
            showMode: showMode
        }, () => {
            this.updateButtonStatus()
        })
        if (oldMode === showMode) {
            return;
        }
        if ('edit' === showMode) {
            this.props.editTable.setStatus(tableid, 'edit');

            // this.props.editTable.setColEditableByKey(tableid, "enablestate",false)
        } else {
            this.props.editTable.cancelEdit(tableid);
        }
    }

    // 获取点击行数据
    getRowData(p, m, r) {
        let checkedArr = [];
        checkedArr.push(r);
        this.setState({
            checkedRowData: checkedArr
        })
    }

    //是有可以修改数据
    isEditTableData() {
        let allTableData = this.props.editTable.getAllRows(tableid);
        let modelInfo = {
            isEditData: ({
                rows: allTableData
            }),
            model: ({
                rows: this.state.checkedRowData
            }),
            'pk_org': this.state.queryActionPkorg
        }
        // this.props.editTable.setEditableByKey(tableid,rowid,0,true);
        // this.props.editTable.setEditableRowKeyByIndex(tableid, Number(1), 'org_infoitem', false)
        ajax({
            url: '/nccloud/hrhi/seqcontrol/EditSeqcontrolOrgAction.do',
            type: 'post',
            data: modelInfo,
            success: res => {
                // let rowid = res.data;
                // let org_pk = this.state.queryActionPkorg;
                // this.props.editTable.setEditableRowByIndex(tableid,[1,2,3],false);
                // this.props.editTable.setEditableRowByRowId(tableid,'166910.b7773bb6418718a', 'isallowedit', false);
                // this.props.editTable.setEditableByKey(tableid, '283970.7869649b9152176', 'isallowedit', true);
                // this.props.editTable.setEditableRowKeyByRowId(tableid,'283970.7869649b9152176','isallowedit', false);
                // this.props.editTable.setEditableRowByRowId(tableid,'283970.7869649b9152176', 'isallowedit', false);
                // this.props.editTable.setEditableRowKeyByIndex(tableid, Number(1), ['isallowedit','memo'], false)
                if (res.success) {
                    let numArr = [];
                    !!res.data.length && res.data.map((v, i) => {
                        numArr.push(parseInt(v));
                    });
                    this.updateShowMode('edit');
                    this.props.editTable.setEditableRowByIndex(tableid, numArr, false);
                }
            },
            error: rej => {
                toast({color: "warning", content: rej.message})
            }
        })
        // this.props.editTable.setStatus(tableid,'edit');
        // this.props.editTable.setEditableRowByRowId(tableid,["063810.1a36760048488037","063810.1a36760048488037"],true)
    }

    //获取某一处修改的数据索引
    searchIndex(arr, id) {
        for (let i = 0; i < arr.length; i++) {
            if (arr[i].rowid == id) {
                return i;
            }
        }
    }

    //编辑数据后重组
    checkedOrNot(a, b, c, d, e, f, g, h) {
        let index = this.searchIndex(modifyDataArr, g.rowid);
        if (index >= 0) {
            modifyDataArr.splice(index, g);
        } else {
            modifyDataArr.push(g);
        }
    }

    // 打印
    print(tableid) {
        printPage.call(this, tableid);
    }

    // 统一处理按钮事件
    onBtnOperation(props, btncode, areacode, opt, recordRow, index) {
        let pk_id = '';
        let record = null;
        if (recordRow) {
            record = JSON.parse(JSON.stringify(recordRow));
            pk_id = record.values.pk_dataio_intface.value;
            this.setState({'row_id': pk_id})
        }
        switch (btncode) {
            case 'edit':
                this.isEditTableData();
                // this.props.form.setFormStatus(tableid, 'edit');
                // this.props.form.EmptyAllFormValue(tableid);
                // this.assignStepModal.show('assign', 'add', '');
                break;
            // case 'reset':
            //     this.promptBoxModal();
            // break;
            case 'refresh':
                this.refreshTableData();
                break;
            case 'save':
                this.saveTableData();
                break;
            case 'cancel':
                let lan2 = this.state.json['hihr-000002'];
                this.promptBoxModal(lan2, this.updateShowMode.bind(this), 'browse');
                break;
            case 'print':
                this.print(tableid);
                break;
            case 'output':
                this.print(tableid);
                break;
            default:
                break;

        }

    }

    /**
     * 查询主组织 节点信息
     */
    searchChange(val) {
        let refpk = val.refpk;
        this.setState({
            queryActionPkorg: refpk,
            hrDeptTreeRef: val
        }, () => {
            this.fetchTableData(refpk);
        })
    }

    // selectedChange(a,b,c,d,e){
    // }
    onBeforeEvent(props, moduleId, item, index, value, record) {
        let {pk_org} = this.state;
        let model = {
            rows: [record]
        };
        let key = item.attrcode;
        ajax({
            url: '/nccloud/hrhi/seqcontrol/BeforeEditSeqcontrolAction.do',
            type: 'post',
            data: {
                pk_org: pk_org,
                model: model,
                item_key: key
            },
            success: res => {
                if (res.success) {
                    let isDisabled = res.data;
                    this.props.editTable.setEditableRowKeyByIndex(moduleId, index, key, isDisabled);
                }
            }
        })
        return true;
    }

    render() {
        let {button, editTable} = this.props;
        let {createButtonApp} = button;
        let {createEditTable} = editTable;
        return (
            <div className="nc-single-table" ref="getContainerDom">
                <div className="nc-singleTable-header-area" ref="getHeaderDom">
                    {/* 按钮区  btn-group */}
                    <div className={'leftDepartmentChoose'}>
                        <ReferSearch
                            orgVal={this.state.hrDeptTreeRef}
                            getOrgData={this.searchChange.bind(this)}
                        />
                    </div>
                    <div className="header-button-area">
                        {createButtonApp({
                            area: 'head',//按钮注册中的按钮区域
                            buttonLimit: 1,
                            onButtonClick: (props, btncode) => this.onBtnOperation(props, btncode, 'list', this),
                            popContainer: document.querySelector('.header-button-area')
                        })}
                    </div>
                </div>

                <div className='nc-singleTable-table-area"' id="tableListData">
                    {/* 生成表格 */}
                    {createEditTable(tableid, {
                        showIndex: true,        //显示序列号
                        onRowClick: this.getRowData,
                        // onBeforeEvent: this.onBeforeEvent,
                        // selectedChange: this.selectedChange.bind(this),
                        onAfterEvent: this.checkedOrNot,            //表格状态监听
                        // height: tableHeight
                        adaptionHeight: true
                    })}
                </div>
            </div>
        );
    }
}

const HomePage = handleHash('201908241349', 'c=60070530&p=60070530p')(createPage({})(MainPage));
ReactDOM.render(<HomePage/>, document.querySelector('#app'));
export default MainPage;
